import * as mockServer from '../../mock/index.js'
var Flyio = require('flyio/dist/npm/wx')
var fly = new Flyio()
import store from '@/stores'

let BASE_URL
process.env.NODE_ENV === 'development'
  ? (BASE_URL = 'http://pad-test-api.shenzhoutianyu.com')
  : (BASE_URL = 'http://pad-test-api.shenzhoutianyu.com')

fly.config = {
  timeout: 30 * 100,
  baseURL: BASE_URL,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
}

function handlingTheMockInterface(request) {
  const { url, body } = request
  return mockServer.resMockData(url, body)
}

//添加请求拦截器
fly.interceptors.request.use((request) => {
  // 发送mock接口
  const reg = /^\/mock.*/
  const isMock = reg.test(request.url)
  if (isMock) {
    let reqResult = handlingTheMockInterface(request)
    return Promise.resolve(reqResult)
  }

  const token = store.state.user.token //关于token的用法
  if (token) {
    request.headers['X-token'] = token
  }
  request.headers['plateform'] = 'helper'
  //可以显式返回request, 也可以不返回，没有返回值时拦截器中默认返回request
  return request
})

//添加响应拦截器，响应拦截器会在then/catch处理之前执行
fly.interceptors.response.use(
  (response) => {
    uni.hideLoading()
    let { msg, code } = response.data
    if ((code >= 200 && code < 300) || code === 304 || code == null) {
      if (response.request.returnAll) {
        return Promise.resolve(response.data)
      } else {
        return Promise.resolve(response.data.data)
      }
    } else {
      switch (code) {
        case 401:
          uni.redirectTo({
            url: '/pages/login/index'
          })
          store.commit('user/SET_TOKEN', '')
          break
        default:
          break
      }

      uni.showToast({
        title: msg,
        icon: 'none'
      })

      return Promise.reject(response)
    }
  },
  (err) => {
    uni.hideLoading()
    //发生网络错误后会走到这里
    return Promise.resolve('网络错误')
  }
)

export default fly
